import java.util.Arrays;
import java.util.Stack;

//找出一个数组中右边值小于原值最近的元素
public class findRightSmaller {
    public static void main(String[] args) {
        int[] a={1,9,4,5,6,2};
        int[] res = findSmaller(a);
        System.out.println("最后的结果是："+ Arrays.toString(res));
    }
    private static int[] findSmaller(int[] a){
        int[] ans = new int[a.length];
        Stack<Integer> t = new Stack<>();
        for(int i=0;i<a.length;i++){
            final int x = a[i];
            while(!t.empty()&&a[t.peek()]>x){
                ans[t.peek()] = i;
                t.pop();
            }
            t.push(i);
        }
        while(t.empty()){
            ans[t.peek()]=-1;
            t.pop();
        }
        return ans;
    }
}
